<?php

namespace app\command;

use app\common\lib\Common;
use app\model\cron\CronTask;
use app\model\queue\AiImageRequestQueueModel;
use app\model\redis\RedisQueueModel;
use bootstrap\DBListen;
use support\Cache;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use Webman\Config;
use Webman\Event\Event;


class CronQueueMonitor extends Command
{
    protected static $defaultName = 'cron:queue:monitor';
    protected static $defaultDescription = 'cron queue monitor';

    /**
     * @return void
     */
    protected function configure()
    {
        //发布执行结束
        Event::dispatch('console.start', []);

        Common::initTaskConfig();
    }

    /**
     * 队列监听，未执行完就中断的队列，重新压入队列
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        try{
            $startTime = round(microtime(true),4);

            $where = [
                'status'=>0,
                //'name'=>'asyncPlanPartAiImage',
            ];
            $queueData = RedisQueueModel::getInstance()->getWhere($where)->orderBy('created_at','asc')->get();
            foreach ($queueData as $queue){
                $data = json_decode($queue['data'],true);
                $queueKey = '{redis-queue}-waiting'.$queue['name'];
                if(in_array($queue['name'],['requestAiImage','requestAiImageAdmin'])){
                    $redisQueues = \Webman\RedisQueue\Redis::connection('ai_image_consumer')->lRange($queueKey,0,-1);
                }else{
                    $redisQueues = \Webman\RedisQueue\Redis::connection()->lRange($queueKey,0,-1);
                }

                $isHas = false;
                foreach($redisQueues as $q){
                    $qData = json_decode($q, true);
                    if($qData['data']['requestid']==$data['requestid']){
                        $isHas = true;
                        break;
                    }
                }

                //重新压入队列
                if($isHas==false){
                    $data['queueid'] = $queue['queueid'];
                    if(in_array($queue['name'],['asyncGeneratedVideoData'])
                        && ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>1800)
                            || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>1800))
                    ){
                        //如果生成作品已经跑到生图这一步，无需重新压入队列了
//                        $where = ['name'=>'requestAiImage',['data','like',"%{$data['requestid']}%"]];
//                        $count = (new RedisQueueModel())->getWhere($where)->count();
//                        if($count==false){
//                            $packageStr = json_encode([
//                                'id'       => time().rand(),
//                                'time'     => time(),
//                                'delay'    => 0,
//                                'attempts' => 0,
//                                'queue'    => $queue['name'],
//                                'data'     => $data
//                            ]);
//                            \Webman\RedisQueue\Redis::connection()->rpush($queueKey,$packageStr);
//                            $queue->monitor_time = date('Y-m-d H:i:s');
//                            $queue->save();
//                        }

//                        if(in_array($data['queueid'],['345119','345112'])){
//                            $packageStr = json_encode([
//                                'id'       => time().rand(),
//                                'time'     => time(),
//                                'delay'    => 0,
//                                'attempts' => 0,
//                                'queue'    => $queue['name'],
//                                'data'     => $data
//                            ]);
//                            \Webman\RedisQueue\Redis::connection()->rpush($queueKey,$packageStr);
//                            $queue->monitor_time = date('Y-m-d H:i:s');
//                            $queue->save();
//                        }
                    }elseif(in_array($queue['name'],['asyncVideoPart'])
                        && ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>300)
                            || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>300))
                    ){
//                        $packageStr = json_encode([
//                            'id'       => time().rand(),
//                            'time'     => time(),
//                            'delay'    => 0,
//                            'attempts' => 0,
//                            'queue'    => $queue['name'],
//                            'data'     => $data
//                        ]);
//                        \Webman\RedisQueue\Redis::connection()->rpush($queueKey,$packageStr);
//                        $queue->monitor_time = date('Y-m-d H:i:s');
//                        $queue->save();

                    }elseif((in_array($queue['name'],['requestAiImage'])||in_array($queue['name'],['requestAiImageAdmin']))
                        && ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>300)
                            || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>300))
                    ){

                        //生图队列，已经跑到生成中这一步，4分钟还没完成可能是队列重启，丢失了，需要重新压队队列
//                        $aiImageFirst = AiImageRequestQueueModel::getInstance()->getWhere(['requestid'=>$data['requestid']])->first();
//                        if($aiImageFirst && (
//                            ($aiImageFirst['status']==1 && (time()-strtotime($aiImageFirst['start_time']))>240)
//                          || ($aiImageFirst['status']==0 && (time()-strtotime($aiImageFirst['created_at']))>300)
//                        )){
////                            $packageStr = json_encode([
////                                'id'       => time().rand(),
////                                'time'     => time(),
////                                'delay'    => 0,
////                                'attempts' => 0,
////                                'queue'    => $queue['name'],
////                                'data'     => $data
////                            ]);
////                            \Webman\RedisQueue\Redis::connection('ai_image_consumer')->rpush($queueKey,$packageStr);
////                            $queue->monitor_time = date('Y-m-d H:i:s');
////                            $queue->save();
//                        }
                    }elseif(in_array($queue['name'],['oceanengineAttribution'])
                        && ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>300)
                            || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>300))
                    ){

                        //巨量引擎回传队列，已经跑到生成中这一步，4分钟还没完成可能是队列重启，丢失了，需要重新压队队列
                        $packageStr = json_encode([
                            'id'       => time().rand(),
                            'time'     => time(),
                            'delay'    => 0,
                            'attempts' => 0,
                            'queue'    => $queue['name'],
                            'data'     => $data
                        ]);
                        \Webman\RedisQueue\Redis::connection()->rpush($queueKey,$packageStr);
                        $queue->monitor_time = date('Y-m-d H:i:s');
                        $queue->save();
                    }elseif(in_array($queue['name'],['asyncPlanPartAiImage'])){
//                        if(!empty($data['user_planid']) &&
//                            ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>600)
//                                || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>600))
//                        ){
//                            $packageStr = json_encode([
//                                'id'       => time().rand(),
//                                'time'     => time(),
//                                'delay'    => 0,
//                                'attempts' => 0,
//                                'queue'    => $queue['name'],
//                                'data'     => $data
//                            ]);
//                            \Webman\RedisQueue\Redis::connection()->lPush($queueKey,$packageStr);
//                            $queue->monitor_time = date('Y-m-d H:i:s');
//                            $queue->save();
//                        }elseif(!empty($data['user_partid']) &&
//                            ((empty($queue['monitor_time']) && (time()-strtotime($queue['created_at']))>180)
//                                || (!empty($queue['monitor_time']) && (time()-strtotime($queue['monitor_time']))>180))
//                        ){
//                            $packageStr = json_encode([
//                                'id'       => time().rand(),
//                                'time'     => time(),
//                                'delay'    => 0,
//                                'attempts' => 0,
//                                'queue'    => $queue['name'],
//                                'data'     => $data
//                            ]);
//                            \Webman\RedisQueue\Redis::connection()->lPush($queueKey,$packageStr);
//                            $queue->monitor_time = date('Y-m-d H:i:s');
//                            $queue->save();
//                        }
                    }
                }
            }

            $ttls =  round(round(microtime(true),4) - $startTime,4);
            //发布执行结束
            Event::dispatch('console.terminate', ['php webman '.self::$defaultName,['success'],$ttls]);

            return self::SUCCESS;
        }catch (\Throwable $e){
            Common::consoleExecptionReport('php webman '.self::$defaultName,$e);
            return self::FAILURE;
        }

    }

}
